var MongoClient = require('mongodb').MongoClient;

var defaultOption = {
    host: 'localhost',
    port: 27017,
    db: 'test',
    poolSize: 20,
    auth: {
        user: '',
        password: ''
    },
    needAuth: false
};

var url = {
    connStr : ""
};

var queryExecutor = null,db_conn = null,error=null;

function getMongoURL() {
    var authStr = "";
    if(defaultOption.needAuth) {
        authStr = defaultOption.auth.user+":"+defaultOption.auth.password + "@";
    }
    var connStr = "mongodb://"+ authStr + defaultOption.host + ":" +defaultOption.port + "/" +defaultOption.db;
    return connStr;
}


/**
 * create the connection
 *
 * @param option is different part to localhost:27017/test
 * @api private
 */
var conn = function (option, callback) {
    var cb = callback;

    if (arguments.length == 1) {
        cb = option;
    } else if (arguments.length == 2) {
        if (!!option.host)
            defaultOption.host = option.host;
        if (!!option.port)
            defaultOption.port = option.port;
        if (!!option.db)
            defaultOption.db = option.db;
        if (!!option.poolSize)
            defaultOption.poolSize = option.poolSize;
        if (!!option.auth) {
            defaultOption.auth = option.auth;
            defaultOption.needAuth = true;
        } else {
            defaultOption.needAuth = false;
        }
        url.connStr = getMongoURL();

    }

    if (!!cb) {
        if(!!queryExecutor) {
            queryExecutor(cb);
        } else {
            MongoClient.connect(url.connStr,{server:{poolSize : defaultOption.poolSize}}, function (err, db) {
                if(err) {
                    //console.log('EasyMongo : DB ERROR. Fail to get connections...');
                    error = err;
                    cb(error,null);
                    return;
                }
                db_conn = db;
                (queryExecutor = function(callback){
                    console.log('EasyMongo : query started...');
                    callback(error,db_conn);
                })(cb);

            });
        }
    }
};

conn.exitConnections = function(){
    db_conn && db_conn.close();
    console.log("EasyMongo : Process END. Return Connections.");
}

module.exports = conn;

